<?php

if (!defined('CORE_PATH'))
    die('Access Denied');

class GalleryManager extends Manager {

    protected $models = array('Gallery', 'GalleryImage');

    public function __construct() {
        parent::__construct('gallery_images', 'gallery');
        $this->setItemClassName('GalleryImage');
        $this->setCategoryClassName('Gallery');

        // set the view to use with this controller
        $this->view = new GalleryView($this);
    }

    /**
     * Returns an array containing the database records of the galleries
     * present in the database
     * 
     * @param int $start the start offset to load records from
     * @param int $limit the total number of records to load
     * @param array $options an array of potential options to use to filter the results
     * @return array an array containing Gallery Objects
     */
    public function getGalleries($start = 0, $limit = NULL, $options = NULL) {

        $default = array(
            'filter' => array(
                'SiteID' => SITE_ID,
                'Published' => 1
            ),
            'offset' => $start,
            'limit' => $limit
        );

        if (defined('IN_CMS') && IN_CMS) {
            $default = array(
                'filter' => array(
                    'SiteID' => SITE_ID
                ),
                'offset' => $start,
                'limit' => $limit
            );
        }

        if ($options != NULL && is_array($options)) {
            $default = array_merge($default, $options);
        }

        return $this->Gallery->find($default);
    }

    /**
     * Returns a Gallery object containing data representing the Gallery identified
     * by the GalleryTag or ID value
     * 
     * @param mixed $galleryTagOrID a value representing the TAG or ID for the gallery object
     * @return Gallery a gallery object containing the data for gallery
     */
    public function getGallery($galleryTagOrID) {

        $default = array(
            'filter' => array(
                'SiteID' => SITE_ID,
                'OR' => array(
                    'id' => $galleryTagOrID,
                    'GalleryID' => $galleryTagOrID
                )
            )
        );

        return $this->Gallery->findFirst($default);
    }

    /**
     * Returns an array containing the database records for the various images
     *
     * @param mixed $galleryID the gallery tag ID
     * @param int $start the start index of the number of records to load
     * @param int $total the total number of records to load
     */
    public function getImages($galleryTag, $start = 0, $total = NULL) {
        $db = $this->getDatabase();

        $gallery = $this->getGallery($galleryTag);

        return $this->find('GalleryImage', array(
            'filter' => array('GalleryID' => $gallery->getId()),
            'order' => array('id' => 'DESC'),
            'offset' => $start,
            'limit' => $total
        ));
    }

    /**
     * Returns the data for the gallery image specified by the ID as an array 
     *
     * @return array returns an array containing the data record of the image
     */
    public function getImage($id) {

        if (intval($id) > 0) {
            return new GalleryImage(intval($id));
        }

        return null;
    }

    /**
     * Provided specifically for use with the CMS interface. This function creates
     * a new gallery based on the information passed via the POST super global
     */
    public function createNewGallery() {

        $gallery = new Gallery(array(
            'SiteID' => SITE_ID,
            'GalleryID' => $_POST['GalleryTag'],
			'GalleryName' => $_POST['GalleryName'],
            'GalleryFolder' => $_POST['GalleryFolder'],
            'GalleryDescription' => $_POST['GalleryDescription'],
            'AllowComments' => $_POST['AllowComments'],
            'ImageSortOrder' => $_POST['ImageSortOrder'],
            'ImageWidth' => $_POST['ImageWidth'],
            'ThumbnailWidth' => $_POST['ThumbnailWidth']
        ));
        
        $gallery->save();
		
		return $gallery;
    }

    /**
     * Provided specifically for use with the CMS interface. This function updates
     * the currently saved gallery information passed via the POST super global
     */
    public function updateEditedGallery() {
        
        $gallery = new Gallery(array(
            'id' => $_POST['id'],
            'SiteID' => SITE_ID,
            'GalleryID' => $_POST['GalleryTag'],
			'GalleryName' => $_POST['GalleryName'],
            'GalleryFolder' => $_POST['GalleryFolder'],
            'GalleryDescription' => $_POST['GalleryDescription'],
            'AllowComments' => $_POST['AllowComments'],
            'ImageSortOrder' => $_POST['ImageSortOrder'],
            'ImageWidth' => $_POST['ImageWidth'],
            'ThumbnailWidth' => $_POST['ThumbnailWidth']
        ));
        
        $gallery->save();
		
		return $gallery;
    }

    public function updateEditedImage() {
        
        $galleryImage = new GalleryImage( array(
            'ImageName' => $_POST['ImageName'],
            'ImageDescription' => $_POST['ImageDescription'],
            'id' => $_POST['id']
        ));
		
        $galleryImage->save();
		
		return $galleryImage;
    }

    /**
     * @return GalleryImage the image object
     */
    public function uploadAndInsertImage() {

        // cache the reference to the supplied image and thumbnail paths
        $imageURL = $_POST['ImageFile'];
        $thumbURL = $_POST['ThumbPath'];

        // the following lines are a fix to ensure we reference the root
        // folder of the site
        $_POST['ImageFile'] = kan_fix_path($_POST['ImageFile']);
        $_POST['destFolder'] = kan_fix_path($_POST['destFolder']);
        $_POST['destFileName'] = kan_fix_path($_POST['destFileName']);
        $_POST['thumbFolder'] = kan_fix_path($_POST['thumbFolder']);

        // get a reference to the gallery for this image
        $gallery = $this->getGallery($_POST['GalleryID']);

        // include the file upload handlers
        include_once(CMS_PATH . 'utils/fileUpload.php');
        include_once(CMS_PATH . 'utils/thumbgen.php');

        // resize the gallery image to have a smaller standard size
        $fpath = generateThumb($_POST['ImageFile'], $_POST['destFolder'], $gallery->getImageWidth());
        $thumbPath = generateThumb($_POST['ImageFile'], $_POST['thumbFolder'], $gallery->getThumbnailWidth());

        // if the thumb image could not be scaled down, then ensure to make the 
        // thumb path equal to the imageURL
        if ($fpath == $thumbPath) {
            $thumbURL = $imageURL;
        }

        // get a reference to the database
        $db = $this->getDatabase();

        // prepare the sql statement for saving the image
        $galleryImage = new GalleryImage(array(
            'GalleryID' => $_POST['GalleryID'],
            'ImageName' => $_POST['ImageName'],
            'ImageDescription' => $_POST['ImageDescription'],
            'ImageURL' => $imageURL,
            'ImageThumbURL' => $thumbURL
        ));
        $galleryImage->save();

        // return the array of data
        return $galleryImage;
    }

    /**
     * Locates and deletes the Galleries with the specified database record IDs.
     * The process also delete the physical gallery image folder and all content present
     * in those galleries. To delete a single gallery, simply pass in the value of the
     * gallery contained in an array
     *
     * @param array $gal_ids the IDs of the various galleries
     */
    public function deleteSelectedGalleries($gal_ids) {

        if (!is_array($gal_ids)) {
            return;
        }

        // include the CMS file utilities class
        include_once(CMS_PATH . "utils/file_utils.php");

        $db = $this->getDatabase();
        $fileUtils = new FileUtils();

        // before we delete the galleries, we need to delete the physical images
        // used by the galleries
        $galleries = $this->Gallery->find(array(
            'filter' => array('id IN' => $gal_ids)
        ));

        // loop through the returned galleries and delete their folders and all subcontent
        foreach($galleries as $gallery) {
            if ($gallery->getFolder() != "../assets/images/gallery/") {
                $fileUtils->rmdirr(kan_fix_path($gallery->getFolder()));
            }
        }

        // delete the individual galleries and subsequently their associated image records
        $this->Gallery->deleteAll(array('id IN' => $gal_ids));
    }

    /**
     * Locates and deletes the gallery image records, image files and thumbnail image files
     * with the database record IDs specified in the supplied array.
     *
     * @param array $img_ids an array containing the ids of the records to delete
     */
    public function deleteGalleryImages($img_ids) {

        if (!is_array($img_ids)) {
            return;
        }

        // include the CMS file utilities class
        include_once(CMS_PATH . "utils/file_utils.php");
        
        $fileUtils = new FileUtils();

        $images = $this->GalleryImage->find( array(
            'filter' => array('id IN' => $img_ids)
        ));

        foreach($images as $image) {
            $fileUtils->deleteFile(kan_fix_path($image->getData('ImageURL')));
            $fileUtils->deleteFile(kan_fix_path($image->getData('ImageThumbURL')));
        }
        
        $this->GalleryImage->deleteAll(array('id IN' => $img_ids));
    }

    /**
     * Changes the published state of the gallery with the specified ID
     *
     * @param mixed $id the database record ID or ALIAS for the gallery
     */
    public function publishGallery($id, $publish) {

        $this->Gallery->updateAll(array('Published' => $publish), array('id' => $id));
    }

    /**
     *
     * @param type $galleryTag
     * @return type 
     */
    public function isTagUnused($galleryTag) {
        return $this->Gallery->count(array('filter' => array('GalleryID' => $galleryTag))) == 0;
    }

}

?>
